package com.ums.scumspay.common;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Optional;

/**
 * @author wangkui
 * @date 2022/1/11
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Resp<T> implements Serializable {

    private String code;
    private String message;
    private T data;


    public Resp(BizCode bizCode) {
        bizCode = Optional.ofNullable(bizCode).orElse(BizCode.CLIENT_ERROR);
        this.code = bizCode.getCode();
        this.message = bizCode.getMsg();
    }


    public static <T> Resp<T> success() {
        BizCode code = BizCode.SUCCESS;
        return restResult(null, code);
    }


    public static <T> Resp<T> success(T data) {
        BizCode code = BizCode.SUCCESS;
        return restResult(data, code);
    }

    public static <T> Resp<T> error(String msg) {
        return restResult(null, BizCode.DATA_ERROR.getCode(), msg);
    }

    public static <T> Resp<T> error(String msg, T result) {
        return restResult(result, BizCode.SERVER_ERROR.getCode(), msg);
    }


    public static <T> Resp<T> error(BizCode errorCode) {
        return restResult(null, errorCode);
    }

    public static <T> Resp<T> error(BizCode errorCode, String message) {
        if (StringUtils.isNotEmpty(message)){
            errorCode.setDetail(String.format("%s【%s】",errorCode.getMsg(), message));
        }
        return restResult(null, errorCode);
    }

    public static <T> Resp<T> restResult(T data, BizCode bizCode) {
        String message = StringUtils.isEmpty(bizCode.getDetail()) ? bizCode.getMsg() : bizCode.getDetail();
        return restResult(data, bizCode.getCode(), message);
    }

    private static <T> Resp<T> restResult(T data, String code, String msg) {
        Resp<T> apiResult = new Resp();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMessage(msg);
        return apiResult;
    }

    public boolean isSuccess(){
        return StringUtils.equalsIgnoreCase(BizCode.SUCCESS.getCode(), this.code);
    }

}
